package com.scoy.honeymei.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.HttpParams;
import com.ocnyang.cartlayout.bean.CartItemBean;
import com.ocnyang.cartlayout.bean.ICartItem;
import com.ocnyang.cartlayout.listener.CartOnCheckChangeListener;
import com.scoy.honeymei.R;
import com.scoy.honeymei.activity.mall.MallMeActivity;
import com.scoy.honeymei.activity.mall.PaySureActivity;
import com.scoy.honeymei.adapter.CartAdapter0;
import com.scoy.honeymei.base.BaseFragment;
import com.scoy.honeymei.bean.CartBean;
import com.scoy.honeymei.bean.CartShopBean;
import com.scoy.honeymei.bean.GoodsOrderBean;
import com.scoy.honeymei.custem.CartEvent;
import com.scoy.honeymei.custem.LeftSwipeLayout;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;
import com.scoy.honeymei.wxapi.PayEvent;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * ClassName:      com.ocnyang.cartlayoutdemo
 * Description:
 * Author:         GaoZhan & Administrator
 * UpdateDate:     2019/11/5/0005$ 上午 11:38$
 * UpdateRemark:   更新内容
 */
public class CartFragment extends BaseFragment {


    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.checkbox_all)
    CheckBox mCheckBoxAll;
    @BindView(R.id.tv_total_price)
    TextView mTvTotal;
    @BindView(R.id.btn_go_to_pay)
    Button mBtnSubmit;
    @BindView(R.id.nodata_tv)
    TextView nodataTv;
    @BindView(R.id.nor_srl)
    SmartRefreshLayout norSrl;
    private Unbinder unbinder;
    private Context mContext;
    private CartAdapter0 mAdapter;

    private int totalCount;//购物车商品ChildItem的总数量，店铺条目不计算在内
    private int totalCheckedCount;//勾选的商品总数量，店铺条目不计算在内
    private double totalPrice;//勾选的商品总价格

    private ArrayList<CartBean> datalist;
    private List<ICartItem> cartlist;
    private int pageInt;

    public static CartFragment newInstance() {

        Bundle args = new Bundle();
        CartFragment fragment = new CartFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick({R.id.checkbox_all, R.id.btn_go_to_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.checkbox_all:
                mAdapter.checkedAll(((CheckBox) view).isChecked());
                break;
            case R.id.btn_go_to_pay:
                submitEvent();
                break;
        }
    }

    private void submitEvent() {
        if (totalCheckedCount == 0) {
            Toast.makeText(mContext, "你还没有选择任何商品", Toast.LENGTH_SHORT).show();
        } else {
            ArrayList<Integer> checklist = new ArrayList<>();

            int shopId = 0;
            int shopCount = 0;
            String meet = "0.00";
            String fei = "0.00";
            int pos = 0;
            if (mAdapter.getData() != null) {

                for (ICartItem iCartItem : mAdapter.getData()) {
                    if (iCartItem.getItemType() == ICartItem.TYPE_GROUP) {
                        if (iCartItem.isChecked()) {
                            meet = datalist.get(pos).getMeet_money();
                            fei = datalist.get(pos).getFreight();
                        }
                        pos++;
                    }
                    if (iCartItem.getItemType() == ICartItem.TYPE_CHILD) {

                        totalCount++;

                        if (iCartItem.isChecked()) {

                            int shopIdTemp = ((GoodsOrderBean) iCartItem).getShop_id();
                            if (shopIdTemp != shopId) {
                                shopCount++;
                                shopId = shopIdTemp;


                            }
                            checklist.add(((GoodsOrderBean) iCartItem).getGoodscarid());
                        }
                    }
                }

                if (shopCount > 1) {
                    MyUtil.mytoast(mContext, "同时只能选择一个商户的商品进行结算");
                    return;
                }
                Log.e("TAG", "submitEvent: " + MyUtil.intarrToString(checklist));

                Intent intent = new Intent(mContext, PaySureActivity.class);
                intent.putExtra("type", 2);
                intent.putExtra("shopId", shopId);
                intent.putExtra("meet", meet);
                intent.putExtra("freight", fei);
                intent.putExtra("ids", MyUtil.intarrToString(checklist));
                startActivityForResult(intent, 0x98);
            }

        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 0x87:
                norSrl.autoRefresh();
                startActivity(new Intent(mContext, MallMeActivity.class));
                break;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cart0, null, false);
        unbinder = ButterKnife.bind(this, view);
        mContext = getContext();


        initNormal();

        httpCartList();

        return view;
    }

    @Override
    public void initNormal() {
        datalist = new ArrayList<>();

        cartlist = new ArrayList<>();

        mBtnSubmit.setText(getString(R.string.go_settle_X, 0));
        mTvTotal.setText(getString(R.string.rmb_X, 0.00));

        initRV();

        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        norSrl.setOnRefreshListener(refreshLayout -> {
            refreshLayout.finishRefresh(1500);
            cartlist.clear();
            mCheckBoxAll.setChecked(false);

            mBtnSubmit.setText(getString(R.string.go_settle_X, 0));
            mTvTotal.setText(getString(R.string.rmb_X, 0.00));
            totalCheckedCount = 0;

            httpCartList();

        }).setEnableLoadMore(false);


    }

    /**
     * 数据初始化尤其重要
     * 1. childItem 数据全部在 GroupItem 数据的下方，数据顺序严格按照对应关系；
     * 2. GroupItem 下的 ChildItem 数据不能为空；
     * 3. 初始化时如果不需要，所有类型的条目都可以不设置ID，GroupItem也不用设置setChilds()；
     * <p>
     * 列表操作时数据动态的变化设置：
     * 1. 通过 CartAdapter 的 addData、setNewData；
     * 2. 单个添加各个条目可以通过对应的 add 方法；
     * 3. 单独添加一个 GroupItem ,可以把它的 ChildItem 数据放到 setChilds 中。
     */
    private void httpCartList() {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.CART_LIST, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                datalist = new Gson().fromJson(o, new TypeToken<List<CartBean>>() {
                }.getType());
                if (datalist != null && datalist.size() > 0) {
                    nodataTv.setVisibility(View.GONE);

                    for (CartBean daben : datalist) {
                        CartShopBean cartShopBean = new CartShopBean(daben.getShopname(), daben.getShopid());
                        cartShopBean.setItemType(CartItemBean.TYPE_GROUP);
                        cartlist.add(cartShopBean);
                        List<GoodsOrderBean> goodsList = daben.getGoodsList();
                        for (GoodsOrderBean gobean : goodsList) {
                            gobean.setItemType(CartItemBean.TYPE_CHILD);
                        }
                        cartlist.addAll(goodsList);
                    }
                } else {
                    nodataTv.setVisibility(View.VISIBLE);
                    mTvTotal.setText(getString(R.string.rmb_X, 0.00));
                }
                mAdapter.notifyDataSetChanged();
            }

        });

    }

    private void initRV() {
        mAdapter = new CartAdapter0(mContext, cartlist);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter);
        recyclerView.addOnItemTouchListener(new LeftSwipeLayout.OnSwipeItemTouchListener(mContext));
        mAdapter.setOnCheckChangeListener(new CartOnCheckChangeListener(recyclerView, mAdapter) {
            @Override
            public void onCalculateChanged(ICartItem cartItemBean) {
                calculate();
            }
        });
        mAdapter.setOnOneClick(pos -> {
            new AlertDialog.Builder(mContext).setTitle("确认移除商品？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确认", (dialog, which) -> {
                        GoodsOrderBean goodsBean = (GoodsOrderBean) cartlist.get(pos);
                        httpCartDelete(goodsBean.getGoodscarid(), pos);
                    }).show();
        });
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给相关的 textView 进行数据填充
     */
    private void calculate() {
        totalCheckedCount = 0;
        totalCount = 0;
        totalPrice = 0.00;
        int notChildTotalCount = 0;
        if (mAdapter.getData() != null) {
            for (ICartItem iCartItem : mAdapter.getData()) {
                if (iCartItem.getItemType() == ICartItem.TYPE_CHILD) {
                    totalCount++;
                    if (iCartItem.isChecked()) {
                        totalCheckedCount++;
                        totalPrice += Double.parseDouble(((GoodsOrderBean) iCartItem).getMoney()) * ((GoodsOrderBean) iCartItem).getNumber();//todo
                    }
                } else {
                    notChildTotalCount++;
                }
            }
        }

        mBtnSubmit.setText(getString(R.string.go_settle_X, totalCheckedCount));
        mTvTotal.setText(getString(R.string.rmb_X, totalPrice));
        if (mCheckBoxAll.isChecked() && (totalCheckedCount == 0 || (totalCheckedCount + notChildTotalCount) != mAdapter.getData().size())) {
            mCheckBoxAll.setChecked(false);
        }
        if (totalCheckedCount != 0 && (!mCheckBoxAll.isChecked()) && (totalCheckedCount + notChildTotalCount) == mAdapter.getData().size()) {
            mCheckBoxAll.setChecked(true);
        }
    }

    //删除购物车
    private void httpCartDelete(int ids, int pos) {
        HttpParams params = new HttpParams();
        params.put("ids", ids);
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.CART_DELETE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                MyUtil.mytoast(mContext, "删除成功");
               /* datalist.clear();
                httpCartList(0);*/
                mAdapter.removeChild(pos);
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
